package init.luoyu.easymonitor.elastic;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import init.luoyu.easymonitor.base.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * <p>Elasticsearch操作服务类</p>
 * @author LuoYu
 * date 2021/5/12
 */
@Service
@Slf4j
public abstract class ElasticService<T> {


    @Autowired
    protected RestHighLevelClient restHighLevelClient;


    /**
     * <p>新增文档</p>
     * @param indexName  索引名称
     * @param entity     实体数据
     * @return           是否成功
     */
    public Boolean createDocument(String indexName,T entity) {
        String id = CommonUtil.getUUID();
        log.info("新增文档 ----> 索引名称:{} -- 文档id:{}",indexName,id);
        IndexRequest request = new IndexRequest(indexName);
        request.id(id);
        request.source(JSONObject.toJSONString(entity), XContentType.JSON);

        try {
             restHighLevelClient.index(request, RequestOptions.DEFAULT);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * <p>批量保存</p>
     * @param indexName  索引名称
     * @param ts          数据列表
     */
    public void bulkCreateDocument(String indexName, List<T> ts){
        if(CommonUtil.isEmptyCollection(ts)) {
            throw new IllegalArgumentException("保存数据不能为空");
        }
        log.info("批量保存文档 ----> 文档数量:{} -- 保存目标索引:{}",ts.size(),indexName);
        BulkRequest bulkRequest = new BulkRequest();
        for (T t : ts) {
            IndexRequest request = new IndexRequest(indexName);
            request.source(JSONObject.toJSONString(t),XContentType.JSON);
            request.id(CommonUtil.getUUID());
            bulkRequest.add(request);
        }
        try {
            BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            log.info("批量保存文档成功 ----> 保存花费时间:{}",responses.getTook());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("批量保存文档到Elasticsearch时发生错误 ----> Error:{}",e.getMessage());
        }
    }


    /**
     * <p>查询</p>
     * @param indexName         索引名称
     * @param queryBuilder      结构化查询条件构造器
     * @param tClass            需要映射的数据类型
     * @return                  返回数据
     */
    public List<T> queryByBuilder(String indexName,SearchSourceBuilder queryBuilder,Class<T> tClass) throws IOException {
        log.info("查询数据 ----> 索引名称:{}", indexName);
        SearchRequest request = new SearchRequest(indexName);
        request.source(queryBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        if (hits == null || hits.length == 0) {
            return Lists.newArrayList();
        }
        JSONArray jsonArray = new JSONArray();
        for (SearchHit hit : hits) {
            jsonArray.add(hit.getSourceAsMap());
        }
        return jsonArray.toJavaList(tClass);
    }

















}
